import subprocess
from Public import *

from GlobalObj import *


logger = logging.getLogger(__name__)


class Enum:
    def __init__(self, port):
        self.port = port
        self.name = "127.0.0.1:"+str(port)
        self.cmdHeader = adbCMDPath + " -s " + self.name

        self.exceCommand("adb devices")
        self.debugDir = "{}/testpic0{}/".format(WorkPath, self.port)
        self.debugDirDetect = "{}/testpic0{}/detect/".format(WorkPath, self.port)
        self.frames = 0
        logger.info("dev name " + self.name)

        if os.path.exists(self.debugDir) is False:
            os.makedirs(self.debugDir)

        if os.path.exists(self.debugDirDetect) is False:
            os.makedirs(self.debugDirDetect)

        for i in os.listdir(self.debugDirDetect):
            path_file = os.path.join(self.debugDirDetect, i) #取文件绝对路径
            if os.path.isfile(path_file):
                os.remove(path_file)



    def screenCap(self):
        cmd = self.cmdHeader + "  shell screencap /sdcard/Pictures/{}.rgba".format(self.port)
        self.exceCommand(cmd, showLog = True)

        try:
            t1 = time.time()
            path = OriginPicDir + "{}.rgba".format(self.port)
            f = open(path, "rb")  # 打开文件
            data = f.read(800 * 450 * 4 + 12)  # 读取剩下所有内容，文件大时候不要用
            data2 = data[12:]
            data2D = np.frombuffer(buffer=data, dtype=np.uint8, count=800 * 450 * 4, offset=12)
            data2D2 = np.reshape(data2D, (450, 800, 4))
            #print("data2D3 {}".format(data2D2.shape))
            img = cv2.cvtColor(data2D2, cv2.COLOR_BGRA2RGB)
            #print(time.time() - t1)

            path = "{}/{}.png".format(self.debugDir, self.frames)

            cv2.imwrite(path, img)
            logger.info("{} : pic {}".format(self.name, self.frames))
            #cv2.imshow("dd", img)
            #cv2.waitKey()

            f.close()
            self.frames += 1

            if img is not None:
                gPublic.detectShiYong(self, img)

            return img
        except IOError:
            logger.info("Error: 没有找到文件或读取文件失败 ")
            logger.info(path)
            return None

    def click(self, clickPos, delay = 300):
        logger.info("{} delay {} ms".format(clickPos, delay))
        cmd = self.cmdHeader + " shell input tap {} {} ".format(clickPos[0], clickPos[1])
        self.exceCommand(cmd)
        time.sleep(delay / 1000.0)


    def swipe(self, spos, delay = 500):
        logger.info(spos)
        cmd = "{}  shell input swipe {} {} {} {} 300 ".format(self.cmdHeader,spos[0], spos[1], spos[2], spos[3])
        self.exceCommand(cmd)
        time.sleep(delay / 1000.0)

    def putText(self, str, delay = 300):
        logger.info(str)
        cmd = self.cmdHeader + "  shell input text " + str
        self.exceCommand(cmd)
        time.sleep(delay / 1000.0)

    def SendKeyCode(self, KEYCODE, delay = 300):
        cmd = self.cmdHeader + " shell input keyevent " + KEYCODE
        self.exceCommand(cmd)
        time.sleep(delay / 1000.0)

    def exceCommand(self, fcmd, showLog = True):
        resonpse = subprocess.getoutput(fcmd)
        if(showLog):
            logger.info("cmd:" + fcmd)
            logger.info(resonpse)
